/**
 * 
 */
package br.inf.mensageiro.view.listener;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

import br.inf.mensageiro.context.ApplicationContext;
import br.inf.mensageiro.main.Mensageiro;
import br.inf.mensageiro.socket.ClientSocket;
import br.inf.mensageiro.view.MainView;
import br.inf.mensageiro.view.WindowView;


/**
 * This is the Listener class for Main Gui's JTree component.
 * 
 * @author yaragalla Muralidhar.
 */
public class JTreeMouseListener extends MouseAdapter{
	
	private MainView mainGui;
	
	/**
	 * Constructs JTreeMouseListener instance.
	 * 
	 * @param mainGui - MainGui.
	 */
	public JTreeMouseListener(MainView mainGui){
		this.mainGui=mainGui;
	}

	@Override
	public void mouseClicked(MouseEvent e){
		
		if(e.getClickCount()==2){			
			JTree jtree=(JTree)e.getComponent();
			DefaultMutableTreeNode node = (DefaultMutableTreeNode)jtree.getLastSelectedPathComponent();
			if(node.getParent()==null){
				return;
			}
			String nodeName=node.getUserObject().toString();
			String ip=ApplicationContext.getInstance().getHosts().get(nodeName);
			boolean establishConn=true;
			boolean isChatWindowExist=false;			
			if(Mensageiro.ipwindowsViewIdMap.containsKey(ip)){
				List<String> chatIds=Mensageiro.ipwindowsViewIdMap.get(ip);
				for(String chatId:chatIds){
					isChatWindowExist=true;
					WindowView chatGui=Mensageiro.windowViewMap.get(chatId);
					if((!chatGui.isVisible()) || (chatGui.getExtendedState()!=0)){						
						chatGui.setVisible(true);
						chatGui.setExtendedState(0);
						chatGui.toFront();
					}
				}
			}
			
			if(isChatWindowExist){
				int option=JOptionPane.showConfirmDialog(mainGui,
						"alreadyChatWindowExist");
				if(option != JOptionPane.YES_OPTION)
					establishConn=false;
			}
			
			if(establishConn){
				Thread client=new Thread(new ClientSocket(ip));
				client.start();
			}
		}
	}
}
